package pdm.traj.service.impl;

import java.util.ArrayList;
import java.util.List;

import pdm.traj.entity.PartInfo;
import pdm.traj.entity.TrackPoint2;
import pdm.traj.entity.TrajQuery;
import pdm.traj.part.PartPlan;
import pdm.traj.service.GeoService;
import pdm.traj.service.KeyService;
import pdm.traj.util.PathUtil;

public class KeyServiceImpl implements KeyService {
	private PathUtil pu;
	private GeoService geoService = null;
	private PartPlan partPlan;
	private String keyPrefix;
	
	public void init() {
//		System.out.println("KeyServiceImpl: init");
		pu = new PathUtil();
		pu.setMap(PathUtil.linkedDataMap);
		//to modify
		keyPrefix = partPlan.getKeyPrefix();
	}
	
	@Override
	public String getKeyByTP(TrackPoint2 tp) {
		if (tp.isBadTP()) {
			return ("badtp");
		} else {
			return (keyPrefix +"__" + tp.lacid + "_" + tp.cellid + "_" + tp.date + "_" + tp.time.substring(0, 2));
		}
	}
	
	@Override
	public String removeKeyPrefix(String key) {
		if (key != null) {
			if (key.startsWith(keyPrefix)) {
				return key.substring(keyPrefix.length() + 2);
			} else {
				return key;
			}
		} else {
			return null;
		}
	}
	
	@Override
	public List<String> getKeysBySidDuration(List<String> sids,
			String startTime, String endTime) {
		List<String> result = null;
		List<String> pfs = this.getKeyPostfixByDuration(startTime, endTime);
		if (pfs == null || pfs.size() == 0) {
			return result;
		} else {
			result = new ArrayList<String>();
			for (String sid : sids) {
				for (String pf : pfs) {
					result.add(keyPrefix +"__" + sid + "_" + pf);
				}
			}
			return result;
		}
	}

	@Override
	public List<String> getKeysByAllSidDuration(String startTime, String endTime) {
		// TODO Auto-generated method stub
		List<String> allsid = geoService.getAllSids();
		return getKeysBySidDuration(allsid, startTime, endTime);
	}

	@Override
	public List<String> getKeyPostfixByDuration(String startTime, String endTime) {
		List<String> l;
		pu.setMap(PathUtil.linkedDataMap);
		l = pu.getKeyPostfixByDuration(startTime, endTime);
		return l;
	}

	@Override
	public List<String> getKeysByRegionDuration(double x1, double y1,
			double x2, double y2, String startTime, String endTime) {
		// TODO Auto-generated method stub
		return null;
	}

	
	public GeoService getGeoService() {
		return geoService;
	}

	public void setGeoService(GeoService geoService) {
		this.geoService = geoService;
	}

	@Override
	public List<String> getKeysByPartInfoAndQuery(PartInfo partInfo,
			TrajQuery query) {
		List<String> result = getKeysByAllSidDuration(query.getStartTime(), query.getEndTime());
		return result;
	}

	public PartPlan getPartPlan() {
		return partPlan;
	}

	public void setPartPlan(PartPlan partPlan) {
		this.partPlan = partPlan;
	}
	
	
	
}
